package com.gubatian.jdk.analyse.register.client;

/**
 * @Description: 发送心跳到注册服务
 * @auther: gubatian
 * @date: 2021/09/14
 */
public class HeartbeatWork {
    private RegisterClient registerClient;
    private HttpSender httpSender;
    private Daemon daemon;
    public HeartbeatWork(RegisterClient registerClient, HttpSender httpSender) {
        this.registerClient = registerClient;
        this.httpSender = httpSender;
    }

    public void initialize() {
        daemon = new Daemon();
        daemon.start();
    }
    private class Daemon extends Thread {
        @Override
        public void run() {
            HeartbeatRequest heartbeatRequest = new HeartbeatRequest();
            heartbeatRequest.setServiceInstanceId(registerClient.getServiceInstanceId());
            HeartbeatResponse heartbeatResponse = null;
            while (registerClient.isRunning()) {
                try {
                    heartbeatResponse = httpSender.heartbeat(heartbeatRequest);
                    System.out.println("心跳的结果为：" + heartbeatResponse.getStatus() + "......");
                    Thread.sleep(30 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 销毁线程
     */
    public void destroy() {
        daemon.interrupt();
    }
}
